<!-- 字典管理 -->
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Delete, Plus, Search, Refresh, EditPen } from '@element-plus/icons-vue'
import { ElTable } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/http'
import { formatDate } from '@/utils/dateFormatter';//引入全局日期格式化工具
// 分页
import type { ComponentSize, TableInstance } from 'element-plus'
import { useCookies } from '@vueuse/integrations/useCookies'
const cookies = useCookies();
let PageNum = ref(1)
let pageSize = ref(5)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  pageInfoSysnotice();
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  pageInfoSysnotice();
  console.log(`current page: ${val}`)
}
const tableData = ref([])
// 科室名称：
let name = ref('')
// 状态：
let status = ref()
let options = [
  {
    value: '0',
    label: '通知',
  }, {
    value: '1',
    label: '公告',
  }
]
// 字典类型
let type = ref('')
// 总条数
let total = ref(0)



// 添加
let dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const form = ref({
  noticeTitle: '',
  noticeType: '',
  status: '',
  noticeContent: '',
  uname: ''
})

const form2 = ref({
  noticeId:'',
  noticeTitle: '',
  noticeType: '',
  status: '',
  noticeContent: ''
})
const addDict = () => {
  form.value.uname = cookies.get("token");
  //发送http请求
  http.post("/notice/addSysNotice", form.value).then((res) => {
    console.log("成功", res)
    pageInfoSysnotice();
  }).catch((message) => {
    console.log("失败", message)
  })
}
// 修改
const addDict2 = () => {
  http.post("/notice/updateSysNotice", form2.value, {
    headers: {
      "Content-Type": "application/json", // 明确指定JSON格式
      "token": localStorage.getItem("token") // 从存储中获取token
    }
  }).then((res) => {
    console.log("修改成功", res)
    ElMessage.success(res.message) // 添加用户反馈
    pageInfoSysnotice();
  }).catch((error) => {
    console.error("修改失败", error)
    ElMessage.error(error.message )
  }).finally(()=>{
    pageInfoSysnotice();
    //关闭模态框
    dialogupdate.value = false
  })
}
// 修改按钮
const handleEdit = async (index: number, row) => {
  //给表单赋值
  form2.value.noticeId=row.noticeId
  form2.value.noticeTitle=row.noticeTitle
  form2.value.noticeType=row.noticeType
  form2.value.status=row.status
  form2.value.noticeContent=row.noticeContent
  //显示修改模态框
  dialogupdate.value = true;



}
const upadte = () => {

}
//删除
const handleDelete = async (index: number) => {
  http.get("/notice/deleteStatus", {
    params: { noticeId: index } // 将数组转换为逗号分隔的字符串
  }).then((res) => {
    console.log("删除成功", res.data);
    // 删除成功后刷新数据
    pageInfoSysnotice();
  }).catch((error) => {
    console.error("删除失败", error);
  });
}
const form3 = ref({
  noticeId:'',
  noticeTitle: '',
  noticeType: '',
  status: '',
  noticeContent: ''
})
//查看按钮
const selectNotice = async (index: number, row) => {

form3.value.noticeId=row.noticeId
form3.value.noticeTitle=row.noticeTitle
form3.value.noticeType=row.noticeType
form3.value.status=row.status
form3.value.noticeContent=row.noticeContent

//开启查看模态框
dialogFormVisible2.value=true;
}
const open = () => {
  if (multipleSelection.value.length === 0) {
    console.warn("请选择要删除的科室");
    return;
  }

  http.delete("/notice/setSysNoticeStatus", {
    params: { noticeIds: multipleSelection.value.join(',') } // 将数组转换为逗号分隔的字符串
  }).then((res) => {
    console.log("删除成功", res.data);
    // 删除成功后刷新数据
    pageInfoSysnotice();
  }).catch((error) => {
    console.error("删除失败", error);
  });
}
const datele = () => {

}
let dialogupdate = ref(false)
//挂载完成之后获查询广告表
onMounted(() => {
  pageInfoSysnotice();
})
//封装查询所有的方法
function pageInfoSysnotice() {
  // 使用对象形式传递参数，框架会自动处理URL编码和拼接
  http.get("/notice/pageInfoSysnotice", {
    params: {
      pageNum: PageNum.value,
      PageSize: pageSize.value,
      noticeTitle: name.value || undefined,  // 当值为空时传undefined，参数不会出现在URL中
      createBy: type.value || undefined,
      noticeType: status.value || undefined
    }
  }).then((res) => {
    tableData.value = res.list
    total.value = res.total
    console.log("成功")
  }).catch(() => {
    console.log("失败")
  })
}
//全选

// 表格的元素引用
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<number[]>([]) // 存储选中的 deptId
interface dept {
  id: number
  date: string
  name: string
  address: string
}
// 获取选中的用户
const handleSelectionChange = (val: dept[]) => {
  console.log("选中的行数据:", val);
  // 使用 map 方法从选中的行数据中提取 deptId，并将这些 deptId 存储在 multipleSelection 数组中
  multipleSelection.value = val.map(row => row.noticeId);
  console.log("选中的 deptId:", multipleSelection.value);
}
// 切换开关状态
const toggleSwitch = (noticeId, status) => {
  // isChecked.value = !isChecked.value;

  // emit('update:modelValue', isChecked.value); // 触发双向绑定更新
  //发送http请求修改科室状态
  http.get("/notice/UpdateStatus?noticeId=" + noticeId + "&status=" + status).then((res) => {
    console.log("成功", res)
    pageInfoSysnotice();
  }).catch((res) => {
    console.log("失败", res)
  }).finally(() => {
    pageInfoSysnotice();
  })
};
//控制查看模态框
let dialogFormVisible2=ref(false)
</script>

<template>
  <!-- 添加模态框 -->
  <el-dialog v-model="dialogFormVisible" title="添加公告" width="500">
    <el-form :model="form">
      <el-form-item label="公告名称:" :label-width="formLabelWidth">
        <el-input v-model="form.noticeTitle" autocomplete="off" />
      </el-form-item>

      <el-form-item label="公告类型:" :label-width="formLabelWidth">
        <el-radio-group v-model="form.noticeType">
          <el-radio :value="0">通知</el-radio>
          <el-radio :value="1">公告</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="状态:" :label-width="formLabelWidth">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">关闭</el-radio>
          <el-radio :value="0">正常</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="内容:" :label-width="formLabelWidth">
        <el-input v-model="form.noticeContent" style="width: 240px" :rows="2" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addDict">
          确定
        </el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 查看模态框 -->
  <el-dialog v-model="dialogFormVisible2"  width="1000">
    <div class="maintenance-notice">
    <!-- 主标题 -->
    <h1 class="main-title" v-text="form3.noticeTitle">
     
    </h1>

    <!-- 状态栏 -->
    <div class="status-bar">
      <span class="preview-text">Write Preview</span>
      <div class="vertical-group">
        <span>H B I S — 66</span>
        <span class="separator">|</span>
        <span>三 归 区 吃 住</span>
        <span class="separator">|</span>
        <span>田 园 的 小 CB</span>
      </div>
    </div>

    <!-- 内容区块 -->
    <div class="content-section">
      <h2 class="content-title">
        <span class="title-decorator"></span>
        维护内容
      </h2>
      
      <!-- 此处可添加具体内容 -->
      <div class="content-placeholder">
        <span v-if="form3.noticeContent==''">
          [维护内容详情区域]
        </span>
        <span v-text="form3.noticeContent"></span>
        
      </div>
    </div>
  </div>
  
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addDict">
          确定
        </el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改模态框 -->
  <el-dialog v-model="dialogupdate" title="修改公告" width="500">
    <el-form :model="form2">
      <el-form-item label="字典名称:" :label-width="formLabelWidth">
        <el-input v-model="form2.noticeTitle" autocomplete="off" />
      </el-form-item>

      <el-form-item label="公告类型:" :label-width="formLabelWidth">
        <el-radio-group v-model="form2.noticeType">
          <el-radio value="1">公告</el-radio>
          <el-radio value="0">通知</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="状态:" :label-width="formLabelWidth">
        <el-radio-group v-model="form2.status">
          <el-radio value="1">停用</el-radio>
          <el-radio value="0">正常</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="内容:" :label-width="formLabelWidth">
        <el-input v-model="form2.noticeContent" style="width: 240px" :rows="2" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addDict2">
          确定
        </el-button>
        <el-button @click="dialogupdate = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 头部搜索 -->
  <el-row>
    <el-col :span="24">
      公告主题：<el-input v-model="name" style="width: 140px" placeholder="Please input" />
      操作人员：<el-input v-model="type" style="width: 140px" placeholder="Please input" />
      类型： <el-select v-model="status" clearable placeholder="全部" style="width: 140px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button :icon="Search" type="primary" @click="pageInfoSysnotice()">搜索</el-button> <el-button :icon="Refresh"
        type="primary">重置</el-button>
    </el-col>
  </el-row>
  <!-- 添加 修改 删除 -->
  <el-row>
    <el-col :span="14">
      <el-button :icon="Plus" type="primary" @click="dialogFormVisible = true" plain>添加</el-button>
      <el-button :icon="EditPen" type="success" @click="dialogupdate = true" plain>修改</el-button>
      <el-button :icon="Delete" type="danger" @click="open" plain>删除</el-button>
    </el-col>
  </el-row>
  <!--  主体内容-->
  <el-row>
    <el-col :span="24">
      <el-table :data="tableData" style="width: 100%" border stripe ref="multipleTableRef" row-key="noticeId"
        @selection-change="handleSelectionChange" v-model="tableData.noticeId">
        <el-table-column type="selection" width="55">

        </el-table-column>
        <el-table-column label="公告ID" width="120">
          <template #default="scope">{{ scope.row.noticeId }}</template>
        </el-table-column>
        <el-table-column property="公告标题" label="公告标题" width="240">
          <template #default="scope">{{ scope.row.noticeTitle }}</template>
        </el-table-column>
        <el-table-column property="公告类型" label="公告类型" width="240" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.noticeType != 1 ? '通知' : '公告' }}</template>
        </el-table-column>
        <el-table-column property="状态" label="状态">
          <template #default="scope">
            <!-- 滑动单选框容器 -->
            <div class="custom-switch" @click="toggleSwitch(scope.row.noticeId, scope.row.status)">
              <!-- 滑动轨道 -->
              <div class="switch-track" :class="{ 'active': scope.row.status != 1 }">
                <!-- 滑动按钮 -->
                <div class="switch-thumb" :class="{ 'active': scope.row.status != 1 }"></div>
              </div>
              <!-- 可选：状态文本 -->
              <span class="state-text">{{ scope.row.status != 1 ? '禁用' : '可用' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="创建者" label="创建者" width="120">
          <template #default="scope">{{ scope.row.createBy }}</template>
        </el-table-column>
        <el-table-column property="创建时间" label="创建时间" width="240" show-overflow-tooltip>
          <template #default="scope">{{ formatDate(scope.row.createTime, 'YYYY年MM月DD日 HH:mm') }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- 修改 -->
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
              <el-icon>
                <Edit />
              </el-icon>修改
            </el-button>
            <!-- 删除 -->
            <el-button size="small" type="danger" @click="handleDelete(scope.row.noticeId)">
              <el-icon>
                <Delete />
              </el-icon> 删除
            </el-button>
            <!-- 查看 -->
            <el-button size="small" type="success" @click="selectNotice(scope.$index, scope.row)">
              <el-icon>
                <UserFilled />
              </el-icon>查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="PageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 20]" :size="size"
          :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 容器样式 */
.custom-switch {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  user-select: none;
}

/* 滑动轨道 */
.switch-track {
  width: 60px;
  height: 30px;
  background-color: #e0e0e0;
  border-radius: 15px;
  position: relative;
  transition: background-color 0.3s ease;
}

/* 激活状态的轨道颜色 */
.switch-track.active {
  background-color: #4CAF50;
  /* 可自定义激活颜色 */
}

/* 滑动按钮 */
.switch-thumb {
  width: 26px;
  height: 26px;
  background-color: white;
  border-radius: 50%;
  position: absolute;
  top: 2px;
  left: 2px;
  transition: transform 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 激活状态的按钮位置 */
.switch-thumb.active {
  transform: translateX(30px);
  /* 根据轨道宽度调整 */
}

/* 状态文本样式 */
.state-text {
  font-size: 14px;
  color: #666;
  font-weight: bold;
}

/* Add your styles here */
.dialog-footer {
  text-align: right;
}

/* 修改模态框 */
.form-container {
  padding: 20px;
  max-width: 600px;
}

.el-input-number {
  width: 100%;
}

.el-radio-group {
  margin-top: 5px;
}
.maintenance-notice {
  font-family: 'Microsoft YaHei', sans-serif;
  max-width: 800px;
  margin: 20px auto;
  padding: 30px;
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.main-title {
  color: #2c3e50;
  font-size: 24px;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid #3498db;
}

.status-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding: 12px;
  background: #ecf0f1;
  border-radius: 4px;
}

.preview-text {
  font-weight: bold;
  color: #e74c3c;
  letter-spacing: 1px;
}

.vertical-group {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #34495e;
}

.separator {
  color: #95a5a6;
  margin: 0 8px;
}

.content-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.content-title {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #16a085;
  font-size: 20px;
  margin-bottom: 15px;
}

.title-decorator {
  display: inline-block;
  width: 4px;
  height: 24px;
  background: #1abc9c;
  border-radius: 2px;
}

.content-placeholder {
  color: #7f8c8d;
  padding: 15px;
  border: 1px dashed #bdc3c7;
  border-radius: 4px;
  min-height: 200px;
}
</style>
